package com.sisyphus.spinach.ui.configs.impl;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.sisyphus.spinach.R;
import com.sisyphus.spinach.core.INetPageTask;
import com.sisyphus.spinach.network.views.SmartRefreshList;
import com.sisyphus.spinach.network.views.SisyphusToast;
import com.sisyphus.spinach.ui.NetTaskRefreshLoadMore;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

public abstract class DefaultActivityPageTemplate<T> implements IPageTemplate<T> {

    private @LayoutRes int resource;

    private View contentView;

    public DefaultActivityPageTemplate() {
        this(R.layout.sisyphus_template_refresh_recycler_view);
    }

    public DefaultActivityPageTemplate(int resource) {
        this.resource = resource;
    }

    public DefaultActivityPageTemplate(View contentView) {
        this.contentView = contentView;
    }

    @Override
    public View view(@NonNull Activity activity) {
        Window window = activity.getWindow();

        View view = contentView == null
                ? LayoutInflater.from(activity).inflate(resource, ((ViewGroup) window.getDecorView()), false)
                : contentView;

        init(activity, view);

        return view;
    }


    private void init(@NonNull Activity activity, @NonNull View view) {
        if (activity instanceof AppCompatActivity) {
            // find view
            AppCompatActivity appCompatActivity = (AppCompatActivity) activity;
            RecyclerView recyclerView = view.findViewById(R.id.recycler_view);
            SmartRefreshLayout refreshLayout = view.findViewById(R.id.refresh_layout);

            recyclerView.setAdapter(adapter(recyclerView)); // 获取列表adapter
            INetPageTask.Presenter<T, INetPageTask.View<T>> presenter = presenter(); // 获取分页网络任务
            presenter.bind(view(recyclerView, refreshLayout)); // 获取view
            appCompatActivity.getLifecycle().addObserver(presenter);

            // 绑定监听
            refreshLayout.setOnRefreshLoadMoreListener(new NetTaskRefreshLoadMore<>(presenter));

            // 自动请求
            refreshLayout.autoRefresh();
        }
    }


    @Override
    public INetPageTask.View<T> view(RecyclerView recyclerView, SmartRefreshLayout refreshLayout) {
        return new SmartRefreshList<>(recyclerView, refreshLayout, new SisyphusToast<>(recyclerView.getContext()));
//        return new SmartRefreshList<>(recyclerView, refreshLayout);
    }

    public abstract BaseQuickAdapter<T, BaseViewHolder> adapter(RecyclerView recyclerView);

}
